#import "NSObject+CrashHandler.h"
#import <objc/runtime.h>
#import <objc/message.h>

static NSMutableDictionary *objectCounts = nil;

@implementation NSObject (CrashHandler)

+ (void)load {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        objectCounts = [NSMutableDictionary dictionary];
        Method originalInit = class_getInstanceMethod([NSObject class], @selector(init));
        Method swizzledInit = class_getInstanceMethod([NSObject class], @selector(swizzledInit));
        method_exchangeImplementations(originalInit, swizzledInit);
        
        Method originalDealloc = class_getInstanceMethod([NSObject class], NSSelectorFromString(@"dealloc"));
        Method swizzledDealloc = class_getInstanceMethod([NSObject class], @selector(swizzledDealloc));
        method_exchangeImplementations(originalDealloc, swizzledDealloc);
    });
}

- (instancetype)swizzledInit {
    id result = [self swizzledInit]; // 调用原始的init方法
    if (result) {
        NSString *className = NSStringFromClass([self class]);
        NSNumber *count = [objectCounts objectForKey:className] ?: @(0);
        objectCounts[className] = @(count.integerValue + 1);
    }
    return result;
}

- (void)swizzledDealloc {
    NSString *className = NSStringFromClass([self class]);
    NSNumber *count = objectCounts[className];
    if (count.integerValue > 0) {
        objectCounts[className] = @(count.integerValue - 1);
    }
    // 调用原始的dealloc方法
    [self swizzledDealloc];
}

+ (NSArray *)topObjectsWithCount:(NSInteger)count {
    NSArray *sortedObjects = [objectCounts keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        return [obj2 compare:obj1];
    }];
    return [sortedObjects subarrayWithRange:NSMakeRange(0, MIN(count, sortedObjects.count))];
}

+ (NSInteger)objectCountForClass:(NSString *)className {
    @synchronized (objectCounts) {
        NSNumber *count = objectCounts[className];
        return count ? count.integerValue : 0;
    }
}

@end 
